package com.jiehoo.elove.dao;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.jiehoo.elove.annotation.Cachable;
import com.jiehoo.elove.annotation.Evict;

public class EnhanceHanlder implements InvocationHandler {
	Cache cache;
	Object target;

	public EnhanceHanlder(Object target) {
		try {
			this.target = target;
			cache = CacheManager.getInstance().getCacheFactory().createCache(
					Collections.emptyMap());
		} catch (CacheException e) {
			throw new RuntimeException("Can not init cache.");
		}
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		Object result = null;
		if (method.isAnnotationPresent(Cachable.class)) {
			String key = getKey(method, args);
			Object value = cache.get(key);
			if (value == null) {

				value = method.invoke(target, args);
				cache.put(key, value);
			}
			result = value;
		}
		if (method.isAnnotationPresent(Evict.class)) {

		}
		return result;
	}

	private String getKey(Method method, Object[] args) {
		return method.getName() + "-" + args.toString();
	}

}
